/**
 * 上传图片/文件路由
 */

var router = require('express').Router();
var fs = require('fs');
var multer  = require('multer');
var userTool = require('../bin/user');
var assertAlljs = require('../bin/util/assert-alljs');

var upload = multer({
    dest: './data/up_tmp/',
    limits: {
        fileSize : 5 * 1024 * 1024, // 最大5MB
        parts : 20, // 最多20个
        headerPairs : 50, // 请求参数最多50个
    }
});

router.post('/upload', upload.any(), async function(req, res) {
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(user);
    if (await assert(checkMessage))
        return;

    req.files.forEach((fileInfo) => {
        var desDir = "./data/up/" + user._id;
        if (!fs.existsSync(desDir))
            fs.mkdirSync(desDir);
        var desFile = desDir + '/' + fileInfo.originalname;
        var data = fs.readFileSync( fileInfo.path);
        fs.writeFileSync(desFile, data);
        if (fileInfo === req.files[req.files.length - 1]){
            let url = res.locals.rootUrl + '/up/' + user._id + '/' + fileInfo.originalname;
            if (req.query.CKEditor === 'ckeditor'){
                res.end('<script>window.parent.CKEDITOR.tools.callFunction('+req.query.CKEditorFuncNum+',"'+url+'","")</script>');
            } else if (req.query.returnType === 'url'){
                res.end(url);
            } else if (req.query.returnType === 'resourcePage'){
                res.redirect(res.locals.rootUrl + '/upResource.html?url='+url);
            }else {
                res.redirect(url);
            }
        }
    });
    req.behavior.set(JSON.stringify(req.files.map((file) => file.originalname)));
});

module.exports = router;